package asyncTasks;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Looper;
import basicClasses.Messages;
import basicClasses.LoginObject;
import basicClasses.MessageObject;


import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;



public class GetMessages extends
		AsyncTask<LoginObject, Void, ArrayList<MessageObject>>
{
	
	@Override
	protected ArrayList<MessageObject> doInBackground(LoginObject... params)
	{
		//Looper.prepare();
		LoginObject login = params[0];
		// TODO: attempt authentication against a network service.
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g6/get_messages.php");
		ArrayList<MessageObject> messages = new ArrayList<MessageObject>();
		try
		{
			// Convert the login object to XML
			XStream xstream = new XStream(new DomDriver("UTF-8"));
			xstream.alias("Login", LoginObject.class);
			String xml = xstream.toXML(login);

			// Pass the XML as a StringEntity
			StringEntity se = new StringEntity(xml, HTTP.UTF_8);
			se.setContentType("text/xml");
			httppost.setEntity(se);
		
			HttpResponse httpresponse = httpclient.execute(httppost);
			HttpEntity resEntity = httpresponse.getEntity();
			String resp = EntityUtils.toString(resEntity);
			System.out.println("Response from server");
			System.out.println(resp);
			System.out.println("printed resp");
			
			if(resp.equalsIgnoreCase("FALSE"))
			{
				ArrayList<MessageObject> arr = null;
				return arr;
			}
			else
			{
				XStream xStream = new XStream();
				xStream.processAnnotations(new Class[] { Messages.class, MessageObject.class });
				Messages comments = (Messages)xStream.fromXML(resp);
				
				ArrayList<MessageObject> arr = comments.getArray();
				return arr;
				
//				for (MessageObject s : arr)
//				{
//					MessageObject x = s;
//					System.out.println(x.text);
//				}
			}			
		}
		catch (java.io.EOFException e)
		{
			
		}
		catch (ClientProtocolException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return messages;
	}

}